package cn.q3c.web.tool;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.apache.commons.lang3.ArrayUtils;

import cn.keyvalue.ccf.common.util.ImageUtils;
import cn.q3c.download.commons.DownloadUtils;
import cn.q3c.web.tool.dao.ImageDAO;
import cn.q3c.web.tool.object.Image;

@Controller
public class ImageWebService {

	@Autowired
	@Qualifier("imageDAO")
	private ImageDAO imageDAO = null;

	/**
	 * 跳转入口，参数为url，返回是spring中的redirect语法
	 * 原图代理，避免图片失效或者refer的问题
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 * @throws ConfigurationException
	 * @throws SQLException
	 */
	@RequestMapping("/image.do")
	public void processImage(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("target") String targetUrl)
			throws ConfigurationException, IOException, SQLException {
		File file = null;

		// 0.查询数据库记录
		Image image = imageDAO.getImage(targetUrl);
		if (image != null) {
			
			file = new File(image.getLocalfile());			
			imageDAO.updateImageDate(image.getNid());
			
			// 更新文件最后时间
			FileUtils.touch(file);
			
		} else {

			// 1.计算要保存文件的名字
			file = DownloadUtils.getSaveNextFile("images", null);

			// 2.下载文件到本地
			FileUtils.copyURLToFile(new URL(targetUrl), file,
					(int) DateUtils.MILLIS_PER_MINUTE,
					(int) DateUtils.MILLIS_PER_MINUTE);
			
			image = new Image();
			image.setUrl(targetUrl);
			image.setLocalfile(file.toString());
			image.setLength(0);
			image.setWidth(0);
			int[] size = ImageUtils.getImageSize(file);
			if( ArrayUtils.isNotEmpty(size) )
			{
				image.setLength(size[0]);
				image.setWidth(size[1]);
			}

			imageDAO.addImage(image);
		}

		// 3.返回
		OutputStream output = response.getOutputStream();
		FileUtils.copyFile(file, output);
		
		// 4.关闭数据流
		IOUtils.closeQuietly(output);
	}
}